package awk.exchanger;

import java.util.Random;
import java.util.concurrent.Exchanger;

/**
 * @description:
 * @author: wanghaifeng
 * @date: 2021/3/5
 */
public class ExchangerDemo {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(new Producer(exchanger, "Full queue"), "Producer").start();
        new Thread(new Consumer(exchanger, "Empty queue"), "Consumer").start();
    }

    static class Producer implements Runnable {

        private Exchanger<String> exchanger;
        private String queue;

        public Producer(Exchanger<String> exchanger, String queue) {
            this.exchanger = exchanger;
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " exchange " + queue + " out");
                Thread.sleep(1000 + new Random().nextInt(1000));
                String other = exchanger.exchange(queue);
                System.out.println(Thread.currentThread().getName() + " exchange " + other + " back");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {

        private Exchanger<String> exchanger;
        private String queue;

        public Consumer(Exchanger<String> exchanger, String queue) {
            this.exchanger = exchanger;
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " exchange " + queue + " out");
                Thread.sleep(1000 + new Random().nextInt(1000));
                String other = exchanger.exchange(queue);
                System.out.println(Thread.currentThread().getName() + " exchange " + other + " back");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
